package com.project.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.dto.FactoryDto;
import com.project.entity.Factory;
import com.project.service.FactoryRemoteService;
import com.project.service.FactoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController

@Api(tags = "供应商管理")
@RequestMapping("/factory")
public class FactoryController {

    @Autowired
    public FactoryService service;

    @ApiOperation(value = "查询")
    @GetMapping("cutByItem")
    public IPage<Factory> cutByItem(Integer pageNo, String name, String scope) {
        return service.cutByItem(pageNo, name, scope);
    }

    @ApiOperation(value = "添加供应商")
    @PostMapping("addFactory")
    public String addFactory(@Valid Factory factory, BindingResult result) throws JsonProcessingException {
        //判断是否有校验失败信息
        if (result.hasFieldErrors()) {
            //得到校验失败的集合
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            //将错误信息转化为json字符串
            String errorJson = om.writeValueAsString(errorList);
            return errorJson;
        }

        service.addFactory(factory);
        return "ok";
    }

    @ApiOperation(value = "查看供应商信息")
    @GetMapping("findById/{id}")
    public Factory findById(@PathVariable("id") Integer id) {
        return service.findById(id);
    }

    @ApiOperation(value = "修改供应商信息")
    @PutMapping("updateHeadAndPhone/{id}/{head}/{headPhone}")
    public String updateHeadAndPhone(@PathVariable("id") Integer id, @PathVariable("head") String head, @PathVariable("headPhone") String headPhone) {
        service.updateHeadAndPhone(id, head, headPhone);
        return "ok";
    }

}
